package com.xhsj.user.hr.process.hrEntryProcess.service;


import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.process.dto.hrEntryProcess.*;
import com.xhsj.user.hr.process.dto.processDefinition.HandleAuditDto;
import com.xhsj.user.hr.process.hrBecomeRegular.service.TbHrApprovalBecomeRegularApplyService;
import com.xhsj.user.hr.process.hrEntryProcess.entity.*;
import com.xhsj.user.hr.process.hrEntryProcess.mapper.TbHrApprovalEntryApplyMapper;
import com.xhsj.user.hr.process.hrEntryProcess.query.*;
import com.xhsj.user.hr.process.hrInterviewRegistration.entity.TbHrInterviewRegistration;
import com.xhsj.user.hr.process.hrInterviewRegistration.query.ShowInterviewRegistrationDetailQuery;
import com.xhsj.user.hr.process.hrInterviewRegistration.service.TbHrInterviewRegistrationService;
import com.xhsj.user.hr.process.hrLeaveProcess.query.ApprovalHiTaskQuery;
import com.xhsj.user.hr.process.hrLeaveProcess.query.WorkFlowNodeQuery;
import com.xhsj.user.hr.process.processDefinition.query.ProcessNodeQuery;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalHiTaskService;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalTaskService;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalWorkFlowNodeService;
import com.xhsj.user.hr.process.query.ApprovalQuery;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.entity.TbGlobalUserRole;
import com.xhsj.user.hr.system.mapper.TbGlobalRoleMapper;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserRoleService;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.hr.system.vo.MonthCountVo;
import com.xhsj.user.hr.userInfo.entity.*;
import com.xhsj.user.hr.userInfo.query.SalarySettingInfoQuery;
import com.xhsj.user.hr.userInfo.service.*;
import com.xhsj.user.utils.MessageConstant;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotNull;

/**
 * <p>
 * hr流程-入职申请表 服务实现类
 * </p>
 *
 * @author liuqinghua
 * @since Sep 7, 2020 10:42:13 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbHrApprovalEntryApply")
public class TbHrApprovalEntryApplyService extends BaseService<TbHrApprovalEntryApplyMapper, TbHrApprovalEntryApply>{
    // 默认密码
    @Value("${default.password}")
    private String password;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;
    @Autowired
    private TbHrApprovalEntryApplyMapper dao;

    // hr流程_入职申请_教育经历 服务实现类
    @Autowired
    private TbHrApprovalEntryEducationService tbHrApprovalEntryEducationService;

    // hr流程_入职申请_家庭成员 服务实现类
    @Autowired
    private TbHrApprovalEntryFamilyService tbHrApprovalEntryFamilyService;

    // hr流程_入职申请_入职相关文件 服务实现类
    @Autowired
    private TbHrApprovalEntryFileService tbHrApprovalEntryFileService;

    // hr流程_入职申请_语言关联表 服务实现类
    @Autowired
    private TbHrApprovalEntryLanguageService tbHrApprovalEntryLanguageService;

    // hr流程_入职申请_培训经历 服务实现类
    @Autowired
    private TbHrApprovalEntryTrainService tbHrApprovalEntryTrainService;

    // hr流程_入职申请_工作记录 服务实现类
    @Autowired
    private TbHrApprovalEntryWorkService tbHrApprovalEntryWorkService;

    // 流程-任务审核表 服务实现类
    @Autowired
    private TbGlobalApprovalTaskService tbGlobalApprovalTaskService;

    // 角色信息表 Mapper 接口
    @Autowired
    private TbGlobalRoleMapper tbGlobalRoleMapper;

    // 用户表 Mapper 接口
    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;

    // 密码
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    // 用户和角色关联表 服务实现类
    @Autowired
    private TbGlobalUserRoleService tbGlobalUserRoleService;

    // 用户-合同信息表 服务实现类
    @Autowired
    private TbGlobalUserContractService tbGlobalUserContractService;

    // 用户_工作经历 服务实现类
    @Autowired
    private TbGlobalUserWorkService tbGlobalUserWorkService;

    // 用户_教育经历 服务实现类
    @Autowired
    private TbGlobalUserEducationService tbGlobalUserEducationService;

    // 用户_家庭情况 服务实现类
    @Autowired
    private TbGlobalUserFamilyService tbGlobalUserFamilyService;

    // 用户_语言关联表 服务实现类
    @Autowired
    private TbGlobalUserLanguageService tbGlobalUserLanguageService;

    // 用户_薪资情况 服务实现类
    @Autowired
    private TbGlobalUserSalaryService tbGlobalUserSalaryService;

    // 薪资设置 服务实现类
    @Autowired
    private TbGlobalSalarySettingService tbGlobalSalarySettingService;

    // 用户_培训经历 服务实现类
    @Autowired
    private TbGlobalUserTrainService tbGlobalUserTrainService;

    // 用户_相关文件 服务实现类
    @Autowired
    private TbGlobalUserFileService tbGlobalUserFileService;

    // hr面试记录登记表 服务实现类
    @Autowired
    private TbHrInterviewRegistrationService tbHrInterviewRegistrationService;

    // 流程-历史表 服务实现类
    @Autowired
    private TbGlobalApprovalHiTaskService tbGlobalApprovalHiTaskService;

    // 流程设计-流程节点 服务实现类
    @Autowired
    private TbGlobalWorkFlowNodeService tbGlobalWorkFlowNodeService;

    //  用户_详细信息 服务实现类
    @Autowired
    private TbGlobalUserDetailService tbGlobalUserDetailService;

    @Autowired
    private TbHrApprovalBecomeRegularApplyService tbHrApprovalBecomeRegularApplyService;


	/**
	 * 保存
	 * @author liuqinghua
	 * @date Sep 7, 2020 10:42:13 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbHrApprovalEntryApply", allEntries=true)
    public boolean save(TbHrApprovalEntryApply entity) {
        return super.save(entity);
    }

	/**
	 * 通过id获取数据
	 * @author liuqinghua
	 * @date Sep 7, 2020 10:42:13 AM
	 */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbHrApprovalEntryApply getById(Serializable id) {
        return super.getById(id);
    }

	/**
	 * 通过id删除数据
	 * @author liuqinghua
	 * @date Sep 7, 2020 10:42:13 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbHrApprovalEntryApply", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 批量删除数据
	 * @author liuqinghua
	 * @date Sep 7, 2020 10:42:13 AM
	 */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

	/**
	 * 分页查询数据
	 * @author liuqinghua
	 * @date Sep 7, 2020 10:42:13 AM
	 */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbHrApprovalEntryApply> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbHrApprovalEntryApply entity = JSON.parseObject(JSON.toJSONString(data), TbHrApprovalEntryApply.class);
        Page<TbHrApprovalEntryApply> page = new Page(currentPage,pageSize);
        QueryWrapper<TbHrApprovalEntryApply> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

	/**
	 * 查询所有数据
	 * @author liuqinghua
	 * @date Sep 7, 2020 10:42:13 AM
	 */
    @Override
    //@Cacheable(value = "TbHrApprovalEntryApply",sync = true)
    public List<TbHrApprovalEntryApply> selectAll() {
        return super.selectAll();
    }


    /**
     * hr流程-入职申请保存
     * @author liuqinghua
     * @date Sep 7, 2020 10:42:13 AM
     */
    public void saveEntryApply(StartEntryApplyDto data) throws Exception {
        TbHrApprovalEntryApply apply = data.getApply();

        String phoneNumber = apply.getPhoneNumber();
        String idCard = apply.getIdCard();
        String bankAccount = apply.getBankAccount();

        TbHrApprovalEntryApply tbHrApprovalEntryApply = dao.getByPhoneNumber(phoneNumber);
        TbHrApprovalEntryApply tbHrApprovalEntryApply1 = dao.getByIdCard(idCard);
        TbHrApprovalEntryApply tbHrApprovalEntryApply2 = dao.getByBankAccount(bankAccount);

        if (tbHrApprovalEntryApply != null) {
            // 如果相同 表示没有修改
            if (!tbHrApprovalEntryApply.getId().equals(apply.getId())) {
                throw new Exception("手机号码已经存在,请更换!");
            }
        }
            if (tbHrApprovalEntryApply2 != null) {
                // 如果相同 表示没有修改
                if (!tbHrApprovalEntryApply2.getId().equals(apply.getId())) {
                    throw new Exception("银行卡号已经存在,请更换!");
                }

            }

            if (tbHrApprovalEntryApply1 != null) {

                // 如果相同 表示没有修改
                if (!tbHrApprovalEntryApply1.getId().equals(apply.getId())) {
                    throw new Exception("身份证号已经存在,请更换!");
                }

            }



            // 保存入职申请表
        if (!super.save(apply)) {
            throw new Exception("保存入职申请表异常");
        }
        // hr流程_入职申请_教育经历
        List<TbHrApprovalEntryEducation> educationList = data.getEducationList();
        for (TbHrApprovalEntryEducation education: educationList) {
            education.setId(null);
            education.setEntryId(apply.getId());
            if (!tbHrApprovalEntryEducationService.save(education)) {
                throw new Exception("hr流程_入职申请_教育经历异常");
            }
        }
       // hr流程_入职申请_家庭成员
        List<TbHrApprovalEntryFamily> familyList = data.getFamilyList();
        for (TbHrApprovalEntryFamily family: familyList) {
            family.setId(null);
            family.setEntryId(apply.getId());
            if (!tbHrApprovalEntryFamilyService.save(family)) {
                throw new Exception("hr流程_入职申请_家庭成员异常");
            }
        }
        // hr流程_入职申请_入职相关文件
        List<TbHrApprovalEntryFile> fileList = data.getFileList();
        for (TbHrApprovalEntryFile file: fileList) {
            file.setId(null);
            file.setEntryId(apply.getId());
            if (!tbHrApprovalEntryFileService.save(file)) {
                throw new Exception("hr流程_入职申请_入职相关文件异常");
            }
        }
        // hr流程_入职申请_语言关联表
        TbHrApprovalEntryLanguageDto language = data.getLanguageList();
        List<String> languageNameList = language.getLanguage();
        List<Long> dictIdList = language.getDictId();
        for (String languageName: languageNameList) {
            int languageInt = languageNameList.indexOf(languageName);
            TbHrApprovalEntryLanguage tbHrApprovalEntryLanguage = new TbHrApprovalEntryLanguage();
            tbHrApprovalEntryLanguage.setEntryId(apply.getId());
            tbHrApprovalEntryLanguage.setLanguage(languageName);
            for (Long dictId: dictIdList) {
                int dictInt = dictIdList.indexOf(dictId);
                if (languageInt == dictInt) {
                    tbHrApprovalEntryLanguage.setDictId(dictId);
                    if (!tbHrApprovalEntryLanguageService.save(tbHrApprovalEntryLanguage)) {
                        throw new Exception("hr流程_入职申请_语言关联表异常");
                    }
                    break;
                }

            }
        }

        // hr流程_入职申请_培训经历
        List<TbHrApprovalEntryTrain> trainList = data.getTrainList();
        for (TbHrApprovalEntryTrain train: trainList) {
            train.setId(null);
            train.setEntryId(apply.getId());
            if (!tbHrApprovalEntryTrainService.save(train)) {
                throw new Exception("hr流程_入职申请_培训经历异常");
            }
        }
        // hr流程_入职申请_工作记录
        List<TbHrApprovalEntryWork> workList = data.getWorkList();
        for (TbHrApprovalEntryWork work: workList) {
            work.setId(null);
            work.setEntryId(apply.getId());
            if (!tbHrApprovalEntryWorkService.save(work)) {
                throw new Exception("hr流程_入职申请_工作记录异常");
            }
        }

    }

    /**
     * hr流程-入职申请开始
     * @author liuqinghua
     * @date Sep 7, 2020 10:42:13 AM
     */
    public ApprovalQuery startEntryApply(StartEntryApplyDto data) throws Exception {
        ApprovalQuery approvalQuery = new ApprovalQuery();
        // 保存相关的文件
        this.updateMyEntryApply(data);
        TbHrApprovalEntryApply apply = data.getApply();
        if (apply.getSubmitStauts() == 1) {
            // 保存用户
            Long userId = this.saveUser(apply.getId());
            // 执行流程
            approvalQuery = this.startEntryApplyRun(apply,userId);
            // 修改面试登记表是否办理入职 0未办理 1已办理 默认未办理
            TbHrInterviewRegistration tbHrInterviewRegistration = new TbHrInterviewRegistration();
            tbHrInterviewRegistration.setId(apply.getInterviewRegistrationId());
            tbHrInterviewRegistration.setIsEntry(1);
            if (!tbHrInterviewRegistrationService.updateById(tbHrInterviewRegistration)) {
                throw new Exception("修改面试登记表是否办理入职异常");
            }
        }
          return approvalQuery;
    }

    /**
     * 执行开始入职流程启动
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery startEntryApplyRun(TbHrApprovalEntryApply apply,Long userId) throws Exception {
        HandleAuditDto handleAuditDto = new HandleAuditDto();
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        handleAuditDto.setDataId(apply.getId());
        handleAuditDto.setProposerId(loginAppUser.getUserId());
        handleAuditDto.setCreateBy(userId);
        handleAuditDto.setApplyType(4);
        // 执行流程
        ProcessNodeQuery processNodeQuery = tbGlobalApprovalTaskService.startHandleAudit(handleAuditDto,apply.getDepartmentId());
        // 修改产品申请表节点名称和节点id
        return this.updateHrApprovalEntryApply(handleAuditDto,processNodeQuery,apply);
    }

    // 修改节点id和节点名称入职申请
    public ApprovalQuery updateHrApprovalEntryApply(HandleAuditDto data,ProcessNodeQuery processNodeQuery,TbHrApprovalEntryApply apply) throws Exception {
        //修改产品申请表节点名称和节点id
        TbHrApprovalEntryApply tbHrApprovalEntryApply = new TbHrApprovalEntryApply();
        BeanUtils.copyProperties(apply,tbHrApprovalEntryApply);
        tbHrApprovalEntryApply.setId(data.getDataId());
        tbHrApprovalEntryApply.setNodeName(processNodeQuery.getNodeName());
        tbHrApprovalEntryApply.setNodeId(processNodeQuery.getNodeId());
        tbHrApprovalEntryApply.setBusinessId(data.getBusinessId());
        tbHrApprovalEntryApply.setDelFlag(1);
        if (!this.save(tbHrApprovalEntryApply)) {
            throw new Exception("修改入职申请节点名称信息异常");
        }
        // 消息参数
        return tbHrApprovalBecomeRegularApplyService.setApprovalQuery(data.getDataId(),4, MessageConstant.MSG_9,processNodeQuery, tbHrApprovalEntryApply == null?"":tbHrApprovalEntryApply.getRealName());
    }

    /**
     * 入职流程审批
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery approvalEntryApply(HandleAuditDto data) throws Exception {
        // 执行流程
        ProcessNodeQuery processNodeVo = tbGlobalApprovalTaskService.handleAudit(data);

        TbHrApprovalEntryApply byId = this.getById(data.getDataId());
        // 修改产品申请表节点名称和节点id
        ApprovalQuery approvalQuery = updateHrApprovalEntryApply(data, processNodeVo,byId);
        if ("完结".equals(processNodeVo.getNodeName())) {

           // 获取入职相关的信息
            TbHrApprovalEntryApply tbHrApprovalEntryApply = dao.selectById(data.getDataId());
            String phoneNumber = tbHrApprovalEntryApply.getPhoneNumber();

            tbGlobalUserMapper.updateStatusByPhone(phoneNumber,0);

            TbGlobalUser tbGlobalUser = tbGlobalUserMapper.findByPhoneNumber(phoneNumber);

            this.saveUserInfo(tbGlobalUser,tbHrApprovalEntryApply,data);
//            // 创建用户得详细信息
//            this.savetbGlobalUserDetail(tbHrApprovalEntryApply,tbGlobalUser.getUserId());
//
//            // 设置邮箱
//            // 初始化用户权限
//            this.saveRole(tbGlobalUser.getUserId(),tbHrApprovalEntryApply.getRoleId());
//            // 入职合同
//            this.saveContract(data.getDataId(),tbHrApprovalEntryApply,tbGlobalUser.getUserId());
//            // 用户信息-工作经历
//            this.saveUserWork(data.getDataId(),tbGlobalUser.getUserId());
//            // 用户信息-家庭情况
//            this.saveUserFamily(data.getDataId(),tbGlobalUser.getUserId());
//            // 用户信息-教育经历
//            this.saveUserEducation(data.getDataId(),tbGlobalUser.getUserId());
//            // 用户信息-培训经历
//            this.saveUserTrain(data.getDataId(),tbGlobalUser.getUserId());
//            // 用户语言
//            this.saveUserLanguage(data.getDataId(),tbGlobalUser.getUserId());
//            // 用户文件
//            this.saveUserFile(data.getDataId(),tbGlobalUser.getUserId());
//            // 用户记录
//            // 薪资系数工资绩效
//            this.saveSalary(tbGlobalUser.getUserId(),tbHrApprovalEntryApply.getSalary(),tbHrApprovalEntryApply.getIsPeriod());
        }
        return approvalQuery;
    }

    // 保存用户信息
    public void saveUserInfo(TbGlobalUser tbGlobalUser,TbHrApprovalEntryApply tbHrApprovalEntryApply,HandleAuditDto data) throws Exception {
        // 创建用户得详细信息
        this.savetbGlobalUserDetail(tbHrApprovalEntryApply,tbGlobalUser.getUserId());
        // 入职合同
        this.saveContract(data.getDataId(),tbHrApprovalEntryApply,tbGlobalUser.getUserId());
        // 用户信息-工作经历
        this.saveUserWork(data.getDataId(),tbGlobalUser.getUserId());
        // 用户信息-家庭情况
        this.saveUserFamily(data.getDataId(),tbGlobalUser.getUserId());
        // 用户信息-教育经历
        this.saveUserEducation(data.getDataId(),tbGlobalUser.getUserId());
        // 用户信息-培训经历
        this.saveUserTrain(data.getDataId(),tbGlobalUser.getUserId());
        // 用户语言
        this.saveUserLanguage(data.getDataId(),tbGlobalUser.getUserId());
        // 用户文件
        this.saveUserFile(data.getDataId(),tbGlobalUser.getUserId());
        // 用户记录
        // 薪资系数工资绩效
        this.saveSalary(tbGlobalUser.getUserId(),tbHrApprovalEntryApply.getSalary(),tbHrApprovalEntryApply.getIsPeriod());
    }

    // 创建用户得详细信息
    public void savetbGlobalUserDetail( TbHrApprovalEntryApply tbHrApprovalEntryApply,Long userId) throws Exception {
        // 保存用户得详细信息
        TbGlobalUserDetail tbGlobalUserDetail = new TbGlobalUserDetail();
        BeanUtils.copyProperties(tbHrApprovalEntryApply,tbGlobalUserDetail);
        tbGlobalUserDetail.setId(null);
        tbGlobalUserDetail.setUserId(userId);
        // 入职日期
        Date arrivalDate = tbGlobalUserDetail.getArrivalDate();
        // 试用期期限
        if (tbGlobalUserDetail.getIsPeriod() == 0) {
            Integer probationPeriod =  tbGlobalUserDetail.getProbationPeriod();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(arrivalDate);
            calendar.add(Calendar.MONTH, probationPeriod);
            calendar.add(Calendar.DAY_OF_MONTH,-1);
            Date date = calendar.getTime();
            tbGlobalUserDetail.setPositiveDate(date);
//            long probationPeriod = Long.valueOf(tbGlobalUserDetail.getProbationPeriod());
//            long time = arrivalDate.getTime();
//            probationPeriod = probationPeriod*24*60*60*1000;
//            time+=probationPeriod;
//            // 转正日期
//            Date date = new Date(time);
//            tbGlobalUserDetail.setPositiveDate(date);
        }
        if (tbGlobalUserDetail.getIsPeriod() == 1){
            tbGlobalUserDetail.setPositiveDate(arrivalDate);
        }

        if (!tbGlobalUserDetailService.save(tbGlobalUserDetail)) {
            throw new Exception("创建用户得详细信息异常");
        }
    }

    /**
     * 保存用户
     * @author 苏小林
     * @date 2021/2/26 13:32
     * @param: dataId
     */
    public Long saveUser(Long dataId) throws Exception {
        // 创建新用户
        TbGlobalUser tbGlobalUser = new TbGlobalUser();
        // 获取入职相关的信息
        TbHrApprovalEntryApply tbHrApprovalEntryApply = dao.selectById(dataId);
        String phoneNumber = tbHrApprovalEntryApply.getPhoneNumber();

//        tbGlobalUserMapper.deleteByPhone(phoneNumber);

        BeanUtils.copyProperties(tbHrApprovalEntryApply,tbGlobalUser);
        tbGlobalUser.setEntryId(tbHrApprovalEntryApply.getId());
        // 设置密码 positionId
        tbGlobalUser.setPassword(bCryptPasswordEncoder.encode(password));
        // 设置工号
        // 获取最大的工号
        Long maxWorkNum = tbGlobalUserMapper.getMaxWorkNum();
        tbGlobalUser.setWorkNum(maxWorkNum+1);
        tbGlobalUser.setUserName(phoneNumber);
        tbGlobalUser.setPhoneNumber(phoneNumber);
        tbGlobalUser.setFullName(tbHrApprovalEntryApply.getRealName());
        tbGlobalUser.setRoleIds(Arrays.asList(tbHrApprovalEntryApply.getRoleId()));
        tbGlobalUser.setStatus(1);
        if (tbHrApprovalEntryApply.getIsPeriod() == 1) {
            tbGlobalUser.setJobStatus(1);
        }
        tbGlobalUserService.saveUser(tbGlobalUser);
        return tbGlobalUser.getUserId();
    }

    //  初始化用户权限
    public void saveRole(Long userId,Long roleId) throws Exception {
        TbGlobalUserRole tbGlobalUserRole = new TbGlobalUserRole();
        tbGlobalUserRole.setUserId(userId);
        tbGlobalUserRole.setRoleId(roleId);
        if (!tbGlobalUserRoleService.save(tbGlobalUserRole)) {
            throw new Exception(" 初始化用户权限异常");
        }
    }

    // 入职合同
    public void saveContract(Long dataId,TbHrApprovalEntryApply tbHrApprovalEntryApply,Long userId) throws Exception {
        // 获取入职合同文件
        QueryWrapper<TbHrApprovalEntryFile> queryWrapper = new QueryWrapper();
        queryWrapper.eq("file_type",3);
        queryWrapper.eq("entry_id",dataId);
        TbHrApprovalEntryFile one = tbHrApprovalEntryFileService.getOne(queryWrapper);
        TbGlobalUserContract tbGlobalUserContract = new TbGlobalUserContract();
        BeanUtils.copyProperties(tbHrApprovalEntryApply,tbGlobalUserContract);
        if (one != null) {
            BeanUtils.copyProperties(one,tbGlobalUserContract);
        }
        tbGlobalUserContract.setId(null);
        tbGlobalUserContract.setUserId(userId);
        tbGlobalUserContract.setContractType(0);
        tbGlobalUserContract.setDictId(Integer.valueOf(tbHrApprovalEntryApply.getContratType()));
        if (!tbGlobalUserContractService.save(tbGlobalUserContract)){
            throw new Exception("保存入职合同异常");
        }
    }
    // 薪资系数工资绩效
    public void saveSalary(Long userId, BigDecimal salary,Integer isPeriod) throws Exception {
        // 薪资系数
        SalarySettingInfoQuery tbGlobalSalarySettings = tbGlobalSalarySettingService.getSalarySettingInfo();
        if (tbGlobalSalarySettings == null) {
            throw new Exception("薪资系数不能为空");
        }
        TbGlobalUserSalary tbGlobalUserSalary = new TbGlobalUserSalary();
        // 基本工资
        String coefficient = null;
        // 绩效工资
        String probationPeriodSalary = "0";
        // 有试用期
        coefficient = tbGlobalSalarySettings.getBaseSalaryCoefficient();
        if ("0".equals(String.valueOf(isPeriod))) {
            tbGlobalUserSalary.setSalaryType(0);
        }
        if ("1".equals(String.valueOf(isPeriod))) {
            // 绩效工资
            String meritCoefficient = tbGlobalSalarySettings.getMeritCoefficient();
            meritCoefficient = meritCoefficient.replaceAll("\\%", "");
            meritCoefficient = StringUtils.div(meritCoefficient, 100, 2);
            probationPeriodSalary = StringUtils.mul(salary, meritCoefficient,2);
            tbGlobalUserSalary.setSalaryType(1);
        }
        // 基础工资
        coefficient = coefficient.replaceAll("\\%", "");
        coefficient = StringUtils.div(coefficient, 100, 2);
        String basicSalary = StringUtils.mul(salary, coefficient,2);

        // 修改工资
        QueryWrapper<TbGlobalUserSalary> queryWrapper = new QueryWrapper();
        queryWrapper.eq("stauts",0);
        queryWrapper.eq("user_id",userId);
        TbGlobalUserSalary one = tbGlobalUserSalaryService.getOne(queryWrapper);
        if (one != null) {
            tbGlobalUserSalary.setId(one.getId());
        }
        // 保存工资
        tbGlobalUserSalary.setUserId(userId);
        tbGlobalUserSalary.setTotalWage(salary);
        tbGlobalUserSalary.setBasicWage(new BigDecimal(basicSalary));
        tbGlobalUserSalary.setMeritPay(new BigDecimal(probationPeriodSalary));
        tbGlobalUserSalary.setSalaryType(isPeriod);
        if (!tbGlobalUserSalaryService.save(tbGlobalUserSalary)) {
            throw new Exception("保存工资异常");
        }

    }
    // 保存用户信息-工作经历
    public void saveUserWork(Long dataId, Long userId) throws Exception {
        // 获取入职工作经历
        QueryWrapper<TbHrApprovalEntryWork> queryWrapper5 = new QueryWrapper();
        queryWrapper5.eq("entry_id",dataId);
        List<TbHrApprovalEntryWork> workList = tbHrApprovalEntryWorkService.list(queryWrapper5);
        if (workList.size() > 0) {
            for (TbHrApprovalEntryWork work: workList) {
                // 保存用户信息-工作经历
                TbGlobalUserWork tbGlobalUserWork = new TbGlobalUserWork();
                BeanUtils.copyProperties(work,tbGlobalUserWork);
                tbGlobalUserWork.setId(null);
                tbGlobalUserWork.setUserId(userId);
                if (!tbGlobalUserWorkService.save(tbGlobalUserWork)) {
                    throw new Exception("保存用户信息-工作经历异常");
                }
            }

        }
    }

    // 用户文件
    public void saveUserFile(Long dataId, Long userId) throws Exception {
        // 获取入职工作经历
        QueryWrapper<TbHrApprovalEntryFile> queryWrapper5 = new QueryWrapper();
        queryWrapper5.eq("entry_id",dataId);
        List<TbHrApprovalEntryFile> fileList = tbHrApprovalEntryFileService.list(queryWrapper5);
        if (fileList.size() > 0) {
            for (TbHrApprovalEntryFile file: fileList) {
                // 保存用户信息-家庭情况
                TbGlobalUserFile tbGlobalUserFile = new TbGlobalUserFile();
                BeanUtils.copyProperties(file, tbGlobalUserFile);
                tbGlobalUserFile.setId(null);
                tbGlobalUserFile.setUserId(userId);
                if (!tbGlobalUserFileService.save(tbGlobalUserFile)) {
                    throw new Exception("用户文件异常");
                }
            }
        }
    }

    // 用户语言
    public void saveUserLanguage(Long dataId, Long userId) throws Exception {
        // 获取入职工作经历
        QueryWrapper<TbHrApprovalEntryLanguage> queryWrapper5 = new QueryWrapper();
        queryWrapper5.eq("entry_id",dataId);
        List<TbHrApprovalEntryLanguage> languageList = tbHrApprovalEntryLanguageService.list(queryWrapper5);
        if (languageList.size() > 0) {
            for (TbHrApprovalEntryLanguage language: languageList) {
                // 保存用户信息-语言情况
                TbGlobalUserLanguage tbGlobalUserLanguage = new TbGlobalUserLanguage();
                BeanUtils.copyProperties(language, tbGlobalUserLanguage);
                tbGlobalUserLanguage.setId(null);
                tbGlobalUserLanguage.setUserId(userId);
                if (!tbGlobalUserLanguageService.save(tbGlobalUserLanguage)) {
                    throw new Exception("用户语言异常");
                }
            }
        }
    }

    // 用户信息-教育经历
    public void saveUserEducation(Long dataId, Long userId) throws Exception {
        // 获取入职工作经历
        QueryWrapper<TbHrApprovalEntryEducation> queryWrapper5 = new QueryWrapper();
        queryWrapper5.eq("entry_id",dataId);
        List<TbHrApprovalEntryEducation> educationList = tbHrApprovalEntryEducationService.list(queryWrapper5);
        if (educationList.size() > 0) {
            for (TbHrApprovalEntryEducation education : educationList) {
                // 保存用户信息-家庭情况
                TbGlobalUserEducation tbGlobalUserEducation = new TbGlobalUserEducation();
                BeanUtils.copyProperties(education, tbGlobalUserEducation);
                tbGlobalUserEducation.setId(null);
                tbGlobalUserEducation.setUserId(userId);
                if (!tbGlobalUserEducationService.save(tbGlobalUserEducation)) {
                    throw new Exception("用户信息-教育经历异常");
                }
            }

        }
    }

    // 用户信息-培训经历
    public void saveUserTrain(Long dataId, Long userId) throws Exception {
        // 获取入职工作经历
        QueryWrapper<TbHrApprovalEntryTrain> queryWrapper5 = new QueryWrapper();
        queryWrapper5.eq("entry_id",dataId);
        List<TbHrApprovalEntryTrain> trainList = tbHrApprovalEntryTrainService.list(queryWrapper5);
        if (trainList.size() > 0) {
            for (TbHrApprovalEntryTrain train : trainList) {
                // 保存用户信息-家庭情况
                TbGlobalUserTrain tbGlobalUserTrain = new TbGlobalUserTrain();
                BeanUtils.copyProperties(train, tbGlobalUserTrain);
                tbGlobalUserTrain.setId(null);
                tbGlobalUserTrain.setUserId(userId);
                if (!tbGlobalUserTrainService.save(tbGlobalUserTrain)) {
                    throw new Exception("用户信息-培训经历异常");
                }
            }
        }
    }

    // 用户信息-家庭情况
    public void saveUserFamily(Long dataId, Long userId) throws Exception {
        // 获取入职工作经历
        QueryWrapper<TbHrApprovalEntryFamily> queryWrapper5 = new QueryWrapper();
        queryWrapper5.eq("entry_id",dataId);
        List<TbHrApprovalEntryFamily> familyList = tbHrApprovalEntryFamilyService.list(queryWrapper5);
        if (familyList.size() > 0) {
            for (TbHrApprovalEntryFamily family : familyList) {
                // 保存用户信息-家庭情况
                TbGlobalUserFamily tbGlobalUserFamily = new TbGlobalUserFamily();
                BeanUtils.copyProperties(family, tbGlobalUserFamily);
                tbGlobalUserFamily.setId(null);
                tbGlobalUserFamily.setUserId(userId);
                if (!tbGlobalUserFamilyService.save(tbGlobalUserFamily)) {
                    throw new Exception("用户信息-家庭情况异常");
                }
            }
        }
    }

    /**
     * 我的入职申请列表
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public Page<MyEntryApplyListQuery> myEntryApplyList(MyEntryApplyListDto data) {
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        Page<MyEntryApplyListQuery> page = new Page<>(data.getPage(),data.getSize());
       return dao.myEntryApplyList(page,userId,data);
    }

    /**
     * 待审核入职申请列表
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public Page<RunEntryApplyListQuery> runEntryApplyList(RunEntryApplyListDto data) {
        Page<RunEntryApplyListQuery> page = new Page<>(data.getPage(),data.getSize());
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        // 获取用户角色id
        List<Long> roleList = tbGlobalRoleMapper.getRoleListByUserId(userId);
        return dao.runEntryApplyList(page,userId,roleList,data);
    }

    /**
     * 已审核入职申请列表
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public IPage<CompletedEntryApplyQuery> completedEntryApplyList(RunEntryApplyListDto data) {
        Page<CompletedEntryApplyQuery> page = new Page<>(data.getPage(),data.getSize());
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        return dao.completedEntryApplyList(page,userId,data);
    }

    /**
     * 我的入职申请详细信息
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public MyEntryApplyDetailedListQuery myEntryApplyDetailedList(Long dataId) {
        MyEntryApplyDetailedListQuery myEntryApplyDetailedListQuery = new MyEntryApplyDetailedListQuery();
        // 入职申请基本数据
        TbHrApprovalEntryApply tbHrApprovalEntryApply = dao.selectById(dataId);
        if (tbHrApprovalEntryApply != null) {
            Long businessId = tbHrApprovalEntryApply.getBusinessId();
            myEntryApplyDetailedListQuery.setApply(tbHrApprovalEntryApply);
            // 入职相关得数据
            this.myEntryApplyDetailedListCommon(dataId,myEntryApplyDetailedListQuery);
            // 审批意见
            List<ApprovalHiTaskQuery> approvalHiTaskList = tbGlobalApprovalHiTaskService.getApprovalHiTaskList(dataId, businessId);
            myEntryApplyDetailedListQuery.setCommentList(approvalHiTaskList);

            // 流程节点
            List<WorkFlowNodeQuery> workFlowNodeQueries = tbGlobalWorkFlowNodeService.nodeList(businessId);
            myEntryApplyDetailedListQuery.setNodeList(workFlowNodeQueries);
        }
        return myEntryApplyDetailedListQuery;
    }

    public MyEntryApplyDetailedListQuery myEntryApplyDetailedListCommon(Long dataId,MyEntryApplyDetailedListQuery myEntryApplyDetailedListQuery) {

        // hr流程_入职申请_教育经历
        QueryWrapper<TbHrApprovalEntryEducation> queryWrapper = new QueryWrapper();
        queryWrapper.eq("entry_id",dataId);
        List<TbHrApprovalEntryEducation> educationList = tbHrApprovalEntryEducationService.list(queryWrapper);

        // hr流程_入职申请_家庭成员
        QueryWrapper<TbHrApprovalEntryFamily> queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("entry_id",dataId);
        List<TbHrApprovalEntryFamily> familyList = tbHrApprovalEntryFamilyService.list(queryWrapper1);

        // hr流程_入职申请_入职相关文件
        QueryWrapper<TbHrApprovalEntryFile> queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("entry_id",dataId);
        List<TbHrApprovalEntryFile> fileList = tbHrApprovalEntryFileService.list(queryWrapper2);

        // hr流程_入职申请_语言关联表
        TbHrApprovalEntryLanguageQuery tbHrApprovalEntryLanguageQuery = new TbHrApprovalEntryLanguageQuery();
        List<Long> dictIdQuery = new ArrayList<>();
        List<String> languageQuery =  new ArrayList<>();
        QueryWrapper<TbHrApprovalEntryLanguage> queryWrapper3 = new QueryWrapper();
        queryWrapper3.eq("entry_id",dataId);
        List<TbHrApprovalEntryLanguage> languageList = tbHrApprovalEntryLanguageService.list(queryWrapper3);
        for (TbHrApprovalEntryLanguage language: languageList) {
            dictIdQuery.add(language.getDictId());
            languageQuery.add(language.getLanguage());
        }
        tbHrApprovalEntryLanguageQuery.setDictId(dictIdQuery);
        tbHrApprovalEntryLanguageQuery.setLanguage(languageQuery);

        // hr流程_入职申请_培训经历
        QueryWrapper<TbHrApprovalEntryTrain> queryWrapper4 = new QueryWrapper();
        queryWrapper4.eq("entry_id",dataId);
        List<TbHrApprovalEntryTrain> trainList = tbHrApprovalEntryTrainService.list(queryWrapper4);

        // hr流程_入职申请_工作记录
        QueryWrapper<TbHrApprovalEntryWork> queryWrapper5 = new QueryWrapper();
        queryWrapper5.eq("entry_id",dataId);
        List<TbHrApprovalEntryWork> workList = tbHrApprovalEntryWorkService.list(queryWrapper5);
        myEntryApplyDetailedListQuery.setEducationList(educationList);
        myEntryApplyDetailedListQuery.setFamilyList(familyList);
        myEntryApplyDetailedListQuery.setFileList(fileList);
        myEntryApplyDetailedListQuery.setLanguageList(tbHrApprovalEntryLanguageQuery);
        myEntryApplyDetailedListQuery.setTrainList(trainList);
        myEntryApplyDetailedListQuery.setWorkList(workList);
       return myEntryApplyDetailedListQuery;
    }

    /**
     * 我的入职申请删除
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public void deleteMyEntryApply(Long dataId,Long interviewRegistrationId) throws Exception {
        // 删除入职申请基本数据
        if (dao.deleteMyEntryApply(dataId) == 0) {
            throw new Exception("删除入职申请基本数据异常");
        }
       this.deleteMyEntryApplyCommon(dataId);
        // 修改面试登记表是否入职  0未办理 1已办理
        TbHrInterviewRegistration tbHrInterviewRegistration = new TbHrInterviewRegistration();
        tbHrInterviewRegistration.setIsEntry(0);
        tbHrInterviewRegistration.setId(interviewRegistrationId);
        if (!tbHrInterviewRegistrationService.updateById(tbHrInterviewRegistration)) {
            throw new Exception("修改面试登记表是否入职异常");
        }
    }

    /**
     * 我的入职申请删除公共
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public void deleteMyEntryApplyCommon(Long dataId) throws Exception {
        // 删除hr流程_入职申请_教育经历
        tbHrApprovalEntryEducationService.deleteByEntryId(dataId);
        // 删除hr流程_入职申请_家庭成员
        tbHrApprovalEntryFamilyService.deleteByEntryId(dataId);
        // 删除hr流程_入职申请_入职相关文件
        tbHrApprovalEntryFileService.deleteByEntryId(dataId);
        // 删除hr流程_入职申请_语言关联表
        tbHrApprovalEntryLanguageService.deleteByEntryId(dataId);
        // 删除hr流程_入职申请_培训经历
        tbHrApprovalEntryTrainService.deleteByEntryId(dataId);
        // 删除hr流程_入职申请_工作记录
        tbHrApprovalEntryWorkService.deleteByEntryId(dataId);
    }

    /**
     * 我的入职申请修改
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public void updateMyEntryApply(StartEntryApplyDto data) throws Exception {
        TbHrApprovalEntryApply apply = data.getApply();
        // 删除相关入职申请的数据
        this.deleteMyEntryApplyCommon(apply.getId());
        // 保存相关的文件
        this.saveEntryApply(data);
    }

    /**
     * hr流程-入职申请重新提交
     * @author liuqinghua
     * @date Sep 7, 2020 10:42:13 AM
     */
    public ApprovalQuery returnEntryApply(ReturnEntryApplyDto data) throws Exception {
        TbHrApprovalEntryApply apply = data.getApply();
        this.deleteMyEntryApplyCommon(apply.getId());

        ApprovalQuery approvalQuery = new ApprovalQuery();
        // 修改
        StartEntryApplyDto startEntryApplyDto = new StartEntryApplyDto();
        BeanUtils.copyProperties(data,startEntryApplyDto);

        tbGlobalUserMapper.deleteByPhone(apply.getPhoneNumber());

        this.updateMyEntryApply(startEntryApplyDto);

        if (apply.getSubmitStauts() == 1) {
            HandleAuditDto handleAudit = data.getHandleAudit();

            // 删除流程
            tbGlobalApprovalTaskService.delById(handleAudit.getProcessTaskId());

            // 删除历史流程
            tbGlobalApprovalTaskService.delHisTask(handleAudit.getBusinessId(),handleAudit.getDataId());

            // 保存用户
            Long userId = this.saveUser(apply.getId());
            // 执行流程
            approvalQuery = this.startEntryApplyRun(apply,userId);
        }
        return approvalQuery;
    }

    /**
     * 我的入职申请详细信息通过面试登记id
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public Object myEntryApplyDetailedListByRegistrationId(Long interviewRegistrationId,Long entryId) {
        MyEntryApplyDetailedListQuery myEntryApplyDetailedListQuery = new MyEntryApplyDetailedListQuery();
        if (entryId == null) {
            ShowInterviewRegistrationDetailQuery showInterviewRegistrationDetailQuery =
                    tbHrInterviewRegistrationService.showInterviewRegistrationDetail(interviewRegistrationId);
            showInterviewRegistrationDetailQuery.getApply().setId(null);
          return showInterviewRegistrationDetailQuery;
        }else {
            // 入职申请基本数据
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("interview_registration_id", interviewRegistrationId);
            TbHrApprovalEntryApply tbHrApprovalEntryApply = dao.selectOne(queryWrapper);
            if (tbHrApprovalEntryApply != null) {
                myEntryApplyDetailedListQuery.setApply(tbHrApprovalEntryApply);
                // 入职相关得数据
                this.myEntryApplyDetailedListCommon(tbHrApprovalEntryApply.getId(), myEntryApplyDetailedListQuery);
            }
        }
        return myEntryApplyDetailedListQuery;
    }

    /**
     * 查询每月入职人数
     * @author 苏小林
     * @date 2020/9/14 15:53
     * @param: date
     * @return: int[]
     */
    public int[] getCountByDate(String date) {
        Calendar calendar = Calendar.getInstance();
        //获得当前年
        int year=calendar.get(Calendar.YEAR);

        //获得当前时bai间的月份，月份从0开始所以结果要加1
        int month=calendar.get(Calendar.MONTH)+1;
        //定义数组
        int[] countVIP = new int[month];

        if (org.apache.commons.lang3.StringUtils.isBlank(date)) {
            date = year +"";
        } else {
            if (!date.equals(year+"")) {
                countVIP = new int[12];
            }
        }

        List<MonthCountVo> list = dao.getCountByDate(date);
        // 判断当月时间
        String year1 = String.valueOf(LocalDate.now().getYear());
        MonthCountVo cunrrentCountByDate = null;
        if(year1.equals(date))
          cunrrentCountByDate = dao.getCunrrentCountByDate();
        if (list.size() >0 && list != null) {
            for (int i = 0; i < list.size(); i++) {
                MonthCountVo monthCountVo = list.get(i);
                if (monthCountVo != null) {
                    if(cunrrentCountByDate != null && cunrrentCountByDate.getMonth() == monthCountVo.getMonth()){
                        monthCountVo.setCount(cunrrentCountByDate.getCount());
                    }
                    //填充月份对应的数据
                    countVIP[monthCountVo.getMonth()-1] = monthCountVo.getCount();
                }

            }
        }
        return countVIP;
    }

    /**
     * 查询入职时间
     * @author 苏小林
     * @date 2020/9/15 10:41
     * @param: userId
     * @return: java.lang.String
     */
    public String findArrivalDate(Long userId) {
        return dao.findArrivalDate(userId);
    }

    /**
     * 入职流程作废
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery approvalEntryToVoidApply(HandleAuditDto data) throws Exception {

        // 删除用户相关数据
        TbHrApprovalEntryApply tbHrApprovalEntryApply = dao.selectById(data.getDataId());
        String phoneNumber = tbHrApprovalEntryApply.getPhoneNumber();
        tbGlobalUserMapper.deleteByPhone(phoneNumber);

        // 执行流程
        ProcessNodeQuery processNodeVo = tbGlobalApprovalTaskService.handleAudit(data);
        // 修改产品申请表节点名称和节点id
       return updateHrApprovalEntryApply(data, processNodeVo,tbHrApprovalEntryApply);
    }
}
